const Koa = require('koa');
const cors = require('@koa/cors');
const koaBody = require('koa-body');
const path = require("path");
const { getTable, Save, getDb } = require("./utils");
const delay = require('delay');
const fs = require("fs-extra");
const app = new Koa();

const static_ = require('koa-static');

app.use(static_(
  path.join(__dirname, './crud/dist/')
))

app.use(cors());
app.use(koaBody());

app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
});

app.use(async (ctx, next) => {
  if (ctx.url == "/api/db") {
    const result = await getDb();
    ctx.body = result;
  }
  if (ctx.url == "/api/tables") {
    const result = (await getTable(ctx.request.body.tableName)).map(item => ({
      ...item,
      isTable: true,
      isSearch: true,
      isForm: true,
      required: true,
      isSwitch: true,
      stringType: "text",//字符串类型：text:文本框 img:图片框 richText:富文本框
    })).map(item => ({
      ...item,
      isSearch: item.typeName != "decimal",
    }));
    ctx.body = result;
  }
  if (ctx.url == "/api/save") {
    // fs.writeFile("./a.json", JSON.stringify(ctx.request.body, null, 2))
    Save(ctx.request.body);
    await delay(1000);
    ctx.body = { success: true };
  }
});


app.listen(3001);
console.log(`服务正在启动，在3001端口`);
console.log(`- Local:   http://localhost:3001 `);






